<?php

/**
 * @Name  支付工具类
 */

namespace App\Helpers;

use App\Model\PayOrder;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Hyperf\Utils\Context;

class PayUtil
{
    /**
     * 支付宝公共参数
     */
    static function alipayPublicParams($appKey = '',$is_new_alipay=0)
    {
        // 公共配置
        $params = new \Yurun\PaySDK\AlipayApp\Params\PublicParams();
        // 其它配置省略
        // 不使用公钥证书模式
        // $params->isUseAES = false;
        $params->usePublicKeyCert = false;
        // 私有证书文件地址
        // $params->appPrivateKeyFile = __DIR__ . '/../../config/alipay_key/Moyu_PrivateKey_2048.txt';
        // 公有证书文件地址
        // $params->appPublicKeyFile = __DIR__ . '/../../config/alipay_key/Moyu_PublicKey_2048.txt';
        if($is_new_alipay == 0){
            $params->appID = $appKey == config('pay.alipay.agst_app_prefix')
            ? config('pay.alipay.agst_app_id')
            : config('pay.alipay.app_id');
            $appKey = $appKey ?: 'Jinnuo';
            $params->appPrivateKey = file_get_contents(__DIR__ . "/../../config/alipay_key/{$appKey}_PrivateKey_2048.txt");
            $params->appPublicKey = file_get_contents(__DIR__ . "/../../config/alipay_key/{$appKey}_PublicKey_Ali.txt");
        }else if($is_new_alipay == 1){

            //$params->appID = $appKey == config('pay.alipay.app_id_new');

            $params->appID = config('pay.alipay.app_id_new');


            $appKey = $appKey ?: 'Jinnuo';
            $params->appPrivateKey = file_get_contents(__DIR__ . "/../../config/alipay_key/{$appKey}_PrivateKey_2048_new.txt");
            $params->appPublicKey = file_get_contents(__DIR__ . "/../../config/alipay_key/{$appKey}_PublicKey_Ali_new.txt");
        }else if($is_new_alipay == 2){//边边

            //$params->appID = $appKey == config('pay.alipay.app_id_new');

            $params->appID = config('pay.alipay.app_id_new2');


            $appKey = $appKey ?: 'Jinnuo';
            $params->appPrivateKey = file_get_contents(__DIR__ . "/../../config/alipay_key/{$appKey}_PrivateKey_2048_new2.txt");
            $params->appPublicKey = file_get_contents(__DIR__ . "/../../config/alipay_key/{$appKey}_PublicKey_Ali_new2.txt");
        }
        
        // log_info(__CLASS__ . '==' . (__DIR__ . "/../../config/alipay_key/{$appKey}_PublicKey_Ali.txt"));
        return $params;
    }

    /**
     * 支付宝
     */
    static function alipay($payInfo = [])
    {
        // SDK实例化，传入公共配置
        $pay = new \Yurun\PaySDK\AlipayApp\SDK(self::alipayPublicParams($payInfo['app_key'] ?: 'Jinnuo',$payInfo['is_new_alipay']));
        // 支付接口
        $request = new \Yurun\PaySDK\AlipayApp\App\Params\Pay\Request();
        $request->notify_url = config('pay.alipay.notify_url'); // 支付后通知地址（作为支付成功回调，这个可靠）
        $request->businessParams->out_trade_no = $payInfo['out_trade_no']; // 商户订单号
        $request->businessParams->total_amount = $payInfo['total_amount']; // 价格
        $request->businessParams->subject = $payInfo['subject']; // 商品标题
        // 处理
        $pay->prepareExecute($request, $url, $data);
        // return [$request, $url, $data]; // 输出的是可以让app直接请求的url
        return http_build_query($data); // 输出的是可以让app直接使用的参数
    }

    /**
     * 微信公共参数
     */
    static function wechatPublicParams($mchId = '')
    {
	       return false;
        // 公共配置
        $params = new \Yurun\PaySDK\Weixin\Params\PublicParams;
        //微信分配的子商户公众账号ID，服务商、银行服务商需要。
        // $params->sub_appid = 'wx723b0d6db8a79597';
        //证书地址
        // $params->certPath = false;
        //私钥地址
        // $params->keyPath = false;
        //微信支付分配的子商户号，开发者模式下必填，服务商、银行服务商需要。
        // $params->sub_mch_id = false;
        //微信支付分配的商户号
        $params->mch_id = $mchId;
        //API密钥
        $params->key = ConfigUtil::getWechatPayInfo('api_key',$mchId);
        //私钥地址
        $params->appID = ConfigUtil::getWechatPayInfo('app_id',$mchId);
        // log_info(__CLASS__ . '==' . json_encode($params));
        return $params;
    }

    /**
     * 微信支付
     */
    static function wechat($payInfo = [])
    {
	   return false;
        // SDK实例化，传入公共配置
        $pay = new \Yurun\PaySDK\Weixin\SDK(self::wechatPublicParams($payInfo['wx_mch_id']));
        // 支付接口
        $request = new \Yurun\PaySDK\Weixin\APP\Params\Pay\Request;
        $request->body = $payInfo['subject']; // 商品描述
        $request->out_trade_no = $payInfo['out_trade_no']; // 订单号
        $request->total_fee = $payInfo['total_amount']; // 订单总金额，单位为：分
        $request->spbill_create_ip = $payInfo['client_ip']; // 客户端ip，必须传正确的用户ip，否则会报错
        $request->notify_url = config('pay.wechat.notify_url'); // 异步通知地址
        $request->trade_type = 'APP';
        // 调用接口
        $result = $pay->execute($request);
        if ($pay->checkResult()) {
            $clientRequest = new \Yurun\PaySDK\Weixin\APP\Params\Client\Request;
            $clientRequest->prepayid = $result['prepay_id'];
            $pay->prepareExecute($clientRequest, $url, $data);
            return $data; // 需要将这个数据返回给app端
        } else {
            return $pay->getErrorCode() . ':' . $pay->getError();
        }
    }

    /**
     * 支付宝appid获取appkey
     */
    static function aliAppkeyByAppId($appId = '')
    {
        return $appId == config('pay.alipay.agst_app_id')
            ? config('pay.alipay.agst_app_prefix')
            : config('pay.alipay.app_key_prefix');
    }
}
